package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DAO.BaseDAO;
import DTO.Admin;
import serviceImpl.AdminDAO;
import util.UtilMD5;

@WebServlet("/all_admin")
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public AdminServlet(){
	}

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String flag = null;
		flag = request.getParameter("flag");
		switch(flag){
		
		case "update_admin_psw":
			update_admin_psw(request,response);
			break;
		}
		
		
		
	}
	
	protected static void update_admin_psw(HttpServletRequest request, HttpServletResponse response){
		try {
			String old_psw = request.getParameter("old_psw");//页面输入的原密码
			old_psw = UtilMD5.MD5U(old_psw);
			String new_psw = request.getParameter("new_psw");//获取到页面上的新密码
			new_psw = UtilMD5.MD5U(new_psw);
			String id = request.getParameter("id");//获取当前账户的id，用于查询密码
			String sql = "update admin set password=? where id=?";
			BaseDAO<Admin> ad = new AdminDAO();
			Admin admin = new Admin();
			admin = ad.findById(id);
			String old2_psw = admin.getPassword();
			if(old_psw.equals(old2_psw)){
				System.out.println("进入修改方法");
				admin.setId(id);
				admin.setPassword(new_psw);
				ad.update(admin, sql);

				 Cookie[] cks = request.getCookies();

				    
				    for(Cookie ck:cks){
				    	if("username".equals(ck.getName())){
				    		ck.setMaxAge(0);
				    		response.addCookie(ck);
				    	}
				    	if("password".equals(ck.getName())){
				    		ck.setMaxAge(0);
				    		response.addCookie(ck);
				    	}
				    }
				request.getSession().removeAttribute("admin");
				PrintWriter out = response.getWriter();
				out.print("<script>top.location.href='login.jsp';</script>");
				out.flush();
			}else{
				request.setAttribute("msg", "修改失败，密码错误");
				request.getRequestDispatcher("update_admin_psw.jsp").forward(request, response);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	
	
	
	
	
	
	
	
	
	

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
